package com.leyou.gateway.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 这个类：是定时任务类，项目启动就执行，每隔24个小时去授权中心申请一次token
 */
@Slf4j
@Component
public class AppTokenHolder {

    @Autowired
    private AuthClient authClient;

    @Autowired
    private JwtProperties prop;

    /**
     * token刷新的间隔时间
     */
    private static final long LOAD_TOKEN_TIME = 86400000L;

    /**
     * 申请token失败之后，休眠等待的时间
     */
    private static final long LOAD_TOKEN_SLEEP_TIME = 10000L;

    @Getter
    private String token;

    @Scheduled(fixedDelay = LOAD_TOKEN_TIME)
    public void loadTokenTask() throws InterruptedException {
        while (true){
            try {
                this.token = authClient.authorization(prop.getApp().getId(), prop.getApp().getSecret());
                log.info("【网关微服务】申请token成功！");
                break;
            } catch (Exception e) {
                log.error("【网关微服务】申请token失败：{}",e.getMessage());
            }
            // 休眠时间
            Thread.sleep(LOAD_TOKEN_SLEEP_TIME);
        }
    }
}
